package main

import (
	"encoding/binary"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"github.com/gorilla/websocket"
	"io"
	"net"
	"net/http"
	"os"
	"time"
)

var (

	// WebSocket 配置
	upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
		CheckOrigin:     func(r *http.Request) bool { return true },
	}
	wsClients = make(map[*websocket.Conn]bool) // 连接客户端集合

)

type Info struct {
	Type string      `json:"type,omitempty"`
	Data interface{} `json:"data,omitempty"`
}

func handleWebSocket(w http.ResponseWriter, r *http.Request) {
	// 升级请求为 WebSocket 连接
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		fmt.Println("Error upgrading to WebSocket:", err)
		return
	}
	defer func() {
		conn.Close()
		delete(wsClients, conn)
		fmt.Println("WebSocket client disconnected")
	}()

	// 将客户端连接添加到集合中
	wsClients[conn] = true
	fmt.Println("WebSocket client connected")

	// 循环处理 WebSocket 客户端发送的消息（可选）
	for {
		messageType, message, err := conn.ReadMessage()
		if err != nil {
			fmt.Println("Error reading message from WebSocket client:", err)
			break
		}

		switch messageType {
		case websocket.TextMessage:
			fmt.Println("Received text message:", string(message))
		case websocket.BinaryMessage:
			fmt.Printf("Received binary data: %s\n", hex.EncodeToString(message))
		default:
			fmt.Println("Received unknown message type")
		}
	}
}

// 解析注册信息参数上报帧

func Regrec(infoSegment []byte) (string, error) {
	if len(infoSegment) != 4 {
		return "", fmt.Errorf("输入的字节长度不正确，期望长度为4，实际为%d", len(infoSegment))
	}
	timestamp2 := binary.BigEndian.Uint32(infoSegment)
	overTime := time.Unix(int64(timestamp2), 0)
	Regrec_Time := overTime.Format("2006-01-02 15:04:05")
	fmt.Printf("%s\n", Regrec_Time)
	info := Info{
		Type: "Regrec_data_upload",
		Data: map[string]interface{}{
			"Regrec_Time": Regrec_Time,
		},
	}
	dataJson, err := json.Marshal(info)
	if err != nil {
		return "", fmt.Errorf("failed to marshal Regrecdata to JSON: %v", err)

	}
	return string(dataJson), nil
} //设备注册

// 解析设备信息参数信息帧里面的信息段

func Devattri(infoSegment []byte) (string, error) {
	if len(infoSegment) != 88 {
		return "", fmt.Errorf("输入的字节长度不正确，期望长度为88，实际为%d", len(infoSegment))
	}
	// 解析各个数据段
	SIM := string(infoSegment[:20])
	GroupID := binary.BigEndian.Uint16(infoSegment[20:22])
	TowerID := binary.BigEndian.Uint16(infoSegment[22:24])
	Landyard := int(infoSegment[24])
	PosX := float32(binary.BigEndian.Uint32(infoSegment[25:29])) / 100.0
	PosY := float32(binary.BigEndian.Uint32(infoSegment[29:33])) / 100.0
	Forarmlen := float32(binary.BigEndian.Uint32(infoSegment[33:37])) / 100.0
	Rearmlen := float32(binary.BigEndian.Uint32(infoSegment[37:41])) / 100.0
	Towerhathight := float32(binary.BigEndian.Uint32(infoSegment[41:45])) / 100.0
	Towerhight := float32(binary.BigEndian.Uint32(infoSegment[45:49])) / 100.0
	Inslongti := float64(binary.BigEndian.Uint32(infoSegment[49:53])) / 1000000.0
	Inslati := float64(binary.BigEndian.Uint32(infoSegment[53:57])) / 1000000.0
	Leftmax := float32(binary.BigEndian.Uint32(infoSegment[57:61])) / 100.0
	Rightmax := float32(binary.BigEndian.Uint32(infoSegment[61:65])) / 100.0
	CargotoTowerformax := float32(binary.BigEndian.Uint32(infoSegment[65:69])) / 100.0
	CarcyctoTowermin := float32(binary.BigEndian.Uint32(infoSegment[69:73])) / 100.0
	Hookmaxhight := float32(binary.BigEndian.Uint32(infoSegment[73:77])) / 100.0
	Maxload := float32(binary.BigEndian.Uint32(infoSegment[77:81])) / 100.0
	Torquemax := float32(binary.BigEndian.Uint32(infoSegment[81:85])) / 100.0
	Warning := int(infoSegment[85])
	Alert := int(infoSegment[86])
	Illegal := int(infoSegment[87])

	// 可选：打印或返回解析后的数据
	fmt.Printf("SIM 卡号: %s\n", SIM)
	fmt.Printf("GroupID: %d\n", GroupID)
	fmt.Printf("TowerID: %d\n", TowerID)
	fmt.Printf("Landyard 倍率: %d\n", Landyard)
	fmt.Printf("PosX: %.2f\n", PosX)
	fmt.Printf("PosY: %.2f\n", PosY)
	fmt.Printf("Forarmlen: %.2f\n", Forarmlen)
	fmt.Printf("Rearmlen: %.2f\n", Rearmlen)
	fmt.Printf("Towerhathight: %.2f\n", Towerhathight)
	fmt.Printf("Towerhight: %.2f\n", Towerhight)
	fmt.Printf("Inslongti: %.6f\n", Inslongti)
	fmt.Printf("Inslati: %.6f\n", Inslati)
	fmt.Printf("Leftmax: %.2f\n", Leftmax)
	fmt.Printf("Rightmax: %.2f\n", Rightmax)
	fmt.Printf("CargotoTowerformax: %.2f\n", CargotoTowerformax)
	fmt.Printf("CarcyctoTowermin: %.2f\n", CarcyctoTowermin)
	fmt.Printf("Hookmaxhight: %.2f\n", Hookmaxhight)
	fmt.Printf("Maxload: %.2f\n", Maxload)
	fmt.Printf("Torquemax: %.2f\n", Torquemax)
	fmt.Printf("Warning: %d%%\n", Warning)
	fmt.Printf("Alert: %d%%\n", Alert)
	fmt.Printf("Illegal: %d%%\n", Illegal)

	info := Info{
		Type: "device_info_parameters",
		Data: map[string]interface{}{
			"SIM":                SIM,
			"GroupID":            GroupID,
			"TowerID":            TowerID,
			"Landyard":           Landyard,
			"PosX":               PosX,
			"PosY":               PosY,
			"Forarmlen":          Forarmlen,
			"Rearmlen":           Rearmlen,
			"Towerhathight":      Towerhathight,
			"Towerhight":         Towerhight,
			"Inslongti":          Inslongti,
			"Inslati":            Inslati,
			"Leftmax":            Leftmax,
			"Rightmax":           Rightmax,
			"CargotoTowerformax": CargotoTowerformax,
			"CarcyctoTowermin":   CarcyctoTowermin,
			"Hookmaxhight":       Hookmaxhight,
			"Maxload":            Maxload,
			"Torquemax":          Torquemax,
			"Warning":            Warning,
			"Alert":              Alert,
			"Illegal":            Illegal,
		},
	}
	infoJSON, err := json.Marshal(info)
	if err != nil {
		return "", fmt.Errorf("failed to marshal info segment to JSON: %v", err)
	}
	// 返回解析后的数据或适当的数据结构
	return string(infoJSON), nil
} //设备属性

func Timeanalyze(infoSegment []byte) (string, error) {
	if len(infoSegment) != 4 {
		return "", fmt.Errorf("输入的字节长度不正确，期望长度为4，实际为%d", len(infoSegment))
	}
	timestamp2 := binary.BigEndian.Uint32(infoSegment)
	overTime := time.Unix(int64(timestamp2), 0)
	a := overTime.Format("2006-01-02 15:04:05")
	return a, nil
}

func devreal(infoSegment []byte) (string, error) {
	if len(infoSegment) != 50 {
		return "", fmt.Errorf("输入的字节长度不正确，期望长度为50，实际为%d", len(infoSegment))
	}
	uploadtime_real_hex := infoSegment[:4]
	Hight := float32(binary.BigEndian.Uint32(infoSegment[4:8])) / 100.0
	Amplitude := float32(binary.BigEndian.Uint32(infoSegment[8:12])) / 100.0
	Angle := decodeSignedInt32(infoSegment[12:16]) / 100.0
	Load := float32(binary.BigEndian.Uint32(infoSegment[16:20])) / 100.0
	SafeLoad := float32(binary.BigEndian.Uint32(infoSegment[20:24])) / 100.0
	SafeLoadPercentage := float32(infoSegment[24])
	Torque := float32(binary.BigEndian.Uint32(infoSegment[25:29])) / 100.0
	TorqueLoadPercentage := float32(infoSegment[29])
	Windspeed := float32(binary.BigEndian.Uint32(infoSegment[30:34])) / 100.0
	InclinationX := float32(binary.BigEndian.Uint32(infoSegment[34:38])) / 100.0
	InclinationY := float32(binary.BigEndian.Uint32(infoSegment[38:42])) / 100.0
	DevStatus := binary.BigEndian.Uint32(infoSegment[42:46])
	Deepth := float32(binary.BigEndian.Uint32(infoSegment[46:50])) / 100.0

	// 解析设备状态
	CraneStatus := parseCraneStatus(DevStatus & 0x0F)
	TorqueStatus := parseTorqueStatus((DevStatus >> 4) & 0x0F)
	WindspeedStatus := parseWindspeedStatus((DevStatus >> 8) & 0x0F)
	AmplitudeStatus := parseAmplitudeStatus((DevStatus >> 12) & 0x0F)
	HightStatus := parseHightStatus((DevStatus >> 16) & 0x0F)
	InclinationStatus := parseInclinationStatus((DevStatus >> 20) & 0x03)
	RotationStatus := parseRotationStatus((DevStatus >> 24) & 0x0F)
	uploadtime_real, err := Timeanalyze(uploadtime_real_hex)
	if err != nil {
		return "", fmt.Errorf("时间戳解析错误: %v", err)
	}

	fmt.Println("信息段数据长度：", len(infoSegment))
	fmt.Println("解析后的数据：")
	fmt.Printf("上传时间: %s\n", uploadtime_real)
	fmt.Printf("高度: %.2f, 状态: %s\n", Hight, HightStatus)
	fmt.Printf("振幅: %.2f, 状态: %s\n", Amplitude, AmplitudeStatus)
	fmt.Printf("转角 X: %.2f\n", Angle)
	fmt.Printf("载重: %.2f\n", Load)
	fmt.Printf("安全载重: %.2f\n", SafeLoad)
	fmt.Printf("安全载重百分比: %.2f\n", SafeLoadPercentage)
	fmt.Printf("力矩: %.2f, 状态: %s\n", Torque, TorqueStatus)
	fmt.Printf("力矩载重百分比: %.2f\n", TorqueLoadPercentage)
	fmt.Printf("风速: %.2f, 状态: %s\n", Windspeed, WindspeedStatus)
	fmt.Printf("倾斜角度X: %.2f\n", InclinationX)
	fmt.Printf("倾斜角度Y: %.2f\n", InclinationY)
	fmt.Printf("设备状态: %s\n", CraneStatus)
	fmt.Printf("倾角状态: %s\n", InclinationStatus)
	fmt.Printf("回转状态: %s\n", RotationStatus)
	fmt.Printf("深度: %.2f\n", Deepth)
	info := Info{
		Type: "device_realtime_data",
		Data: map[string]interface{}{
			"uploadtime_real":      uploadtime_real,
			"Hight":                Hight,
			"Amplitude":            Amplitude,
			"Angle":                Angle,
			"Load":                 Load,
			"SafeLoad":             SafeLoad,
			"SafeLoadPercentage":   SafeLoadPercentage,
			"Torque":               Torque,
			"TorqueLoadPercentage": TorqueLoadPercentage,
			"Windspeed":            Windspeed,
			"InclinationX":         InclinationX,
			"InclinationY":         InclinationY,
			"DevStatus":            DevStatus,
			"Deepth":               Deepth,
		},
	}

	// 将信息段数据转换为 JSON 格式
	infoJSON, err := json.Marshal(info)
	if err != nil {
		return "", fmt.Errorf("failed to marshal info segment to JSON: %v", err)
	}

	// 返回 JSON 字符串和错误（如果有）
	return string(infoJSON), nil
} //实时数据
func hoistingdata(infoSegment []byte) (string, error) {
	if len(infoSegment) != 78 {
		return "", fmt.Errorf("输入的字节长度不正确，期望长度为78，实际为%d", len(infoSegment))
	}

	uploadtime_hoi_hex := infoSegment[:4]
	Begintime := infoSegment[4:8]
	Endtime := infoSegment[8:12]
	MaxLoad := float32(binary.BigEndian.Uint32(infoSegment[12:16])) / 100.0
	MaxLoadPercentage := uint8(infoSegment[16])
	MaxTorque := float32(binary.BigEndian.Uint32(infoSegment[17:21])) / 100.0
	MaxTorquePercentage := uint8(infoSegment[21])
	BeginAngle := float32(binary.BigEndian.Uint32(infoSegment[22:26])) / 100.0
	EndAngle := float32(binary.BigEndian.Uint32(infoSegment[26:30])) / 100.0
	BeginAmplitude := float32(binary.BigEndian.Uint32(infoSegment[30:34])) / 100.0
	EndAmplitude := float32(binary.BigEndian.Uint32(infoSegment[34:38])) / 100.0
	MaxAmplitude := float32(binary.BigEndian.Uint32(infoSegment[38:42])) / 100.0
	MinAmplitude := float32(binary.BigEndian.Uint32(infoSegment[42:46])) / 100.0
	BeginHight := float32(binary.BigEndian.Uint32(infoSegment[46:50])) / 100.0
	EndHight := float32(binary.BigEndian.Uint32(infoSegment[50:54])) / 100.0
	MaxHight := float32(binary.BigEndian.Uint32(infoSegment[54:58])) / 100.0
	MinHight := float32(binary.BigEndian.Uint32(infoSegment[58:62])) / 100.0
	MaxWindSpeed := float32(binary.BigEndian.Uint32(infoSegment[62:66])) / 100.0
	MaxInclinationX := float32(binary.BigEndian.Uint32(infoSegment[66:70])) / 100.0
	MaxInclinationY := float32(binary.BigEndian.Uint32(infoSegment[70:74])) / 100.0
	DevStatus := binary.BigEndian.Uint32(infoSegment[74:78])

	CraneStatus := parseCraneStatus(DevStatus & 0x0F)
	TorqueStatus := parseTorqueStatus((DevStatus >> 4) & 0x0F)
	WindspeedStatus := parseWindspeedStatus((DevStatus >> 8) & 0x0F)
	AmplitudeStatus := parseAmplitudeStatus((DevStatus >> 12) & 0x0F)
	HightStatus := parseHightStatus((DevStatus >> 16) & 0x0F)
	InclinationStatus := parseInclinationStatus((DevStatus >> 20) & 0x03)
	RotationStatus := parseRotationStatus((DevStatus >> 24) & 0x0F)
	uploadtime_hoi, err := Timeanalyze(uploadtime_hoi_hex)
	if err != nil {
		return "", fmt.Errorf("时间戳解析错误: %v", err)
	}

	fmt.Println("解析后的数据：")
	fmt.Printf("上传时间: %s\n", uploadtime_hoi)
	fmt.Printf("开始时间: %v\n", Begintime)
	fmt.Printf("结束时间: %v\n", Endtime)
	fmt.Printf("最大载重: %.2f\n", MaxLoad)
	fmt.Printf("最大载重百分比: %d%%\n", MaxLoadPercentage)
	fmt.Printf("最大力矩: %.2f\n", MaxTorque)
	fmt.Printf("最大力矩百分比: %d%%\n", MaxTorquePercentage)
	fmt.Printf("起始角度: %.2f\n", BeginAngle)
	fmt.Printf("结束角度: %.2f\n", EndAngle)
	fmt.Printf("起始幅度: %.2f\n", BeginAmplitude)
	fmt.Printf("结束幅度: %.2f\n", EndAmplitude)
	fmt.Printf("最大幅度: %.2f\n", MaxAmplitude)
	fmt.Printf("最小幅度: %.2f\n", MinAmplitude)
	fmt.Printf("起始高度: %.2f\n", BeginHight)
	fmt.Printf("结束高度: %.2f\n", EndHight)
	fmt.Printf("最大高度: %.2f\n", MaxHight)
	fmt.Printf("最小高度: %.2f\n", MinHight)
	fmt.Printf("最大风速: %.2f\n", MaxWindSpeed)
	fmt.Printf("最大倾斜角度X: %.2f\n", MaxInclinationX)
	fmt.Printf("最大倾斜角度Y: %.2f\n", MaxInclinationY)
	fmt.Printf("设备状态: %s\n", CraneStatus)
	fmt.Printf("力矩状态: %s\n", TorqueStatus)
	fmt.Printf("风速状态: %s\n", WindspeedStatus)
	fmt.Printf("幅度状态: %s\n", AmplitudeStatus)
	fmt.Printf("高度状态: %s\n", HightStatus)
	fmt.Printf("倾角状态: %s\n", InclinationStatus)
	fmt.Printf("回转状态: %s\n", RotationStatus)
	info := Info{
		Type: "hoisting_data_upload",
		Data: map[string]interface{}{
			"uploadtime_hoi":      uploadtime_hoi,
			"Begintime":           Begintime,
			"Endtime":             Endtime,
			"MaxLoad":             MaxLoad,
			"MaxLoadPercentage":   MaxLoadPercentage,
			"MaxTorque":           MaxTorque,
			"MaxTorquePercentage": MaxTorquePercentage,
			"BeginAngle":          BeginAngle,
			"EndAngle":            EndAngle,
			"BeginAmplitude":      BeginAmplitude,
			"EndAmplitude":        EndAmplitude,
			"MaxAmplitude":        MaxAmplitude,
			"MinAmplitude":        MinAmplitude,
			"BeginHight":          BeginHight,
			"EndHight":            EndHight,
			"MaxHight":            MaxHight,
			"MinHight":            MinHight,
			"MaxWindSpeed":        MaxWindSpeed,
			"MaxInclinationX":     MaxInclinationX,
			"MaxInclinationY":     MaxInclinationY,
			"CraneStatus":         CraneStatus,
			"TorqueStatus":        TorqueStatus,
			"WindspeedStatus":     WindspeedStatus,
			"AmplitudeStatus":     AmplitudeStatus,
			"HightStatus":         HightStatus,
			"InclinationStatus":   InclinationStatus,
			"RotationStatus":      RotationStatus,
		},
	}

	// 将 JSON 数据编码为字符串
	dataJSON, err := json.Marshal(info)
	if err != nil {
		return "", fmt.Errorf("failed to marshal hoistingdata to JSON: %v", err)
	}

	// 返回 JSON 字符串和错误
	return string(dataJSON), nil
} //塔吊数据
// 解析有符号的32位整数
func decodeSignedInt32(data []byte) float32 {
	val := binary.BigEndian.Uint32(data)
	if val&(1<<31) != 0 { // 检查最高位是否为1，表示负数
		// 转换为补码形式
		val = ^val + 1
		// 转换为有符号整数并取负值
		return -float32(val)
	}
	return float32(val)
}

// 解析起重状态
func parseCraneStatus(status uint32) string {
	switch status {
	case 0:
		return "正常"
	case 1:
		return "预警"
	case 2:
		return "报警"
	case 3:
		return "违章"
	case 4:
		return "故障"
	default:
		return "未知"
	}
}

// 解析力矩状态
func parseTorqueStatus(status uint32) string {
	switch status {
	case 0:
		return "正常"
	case 1:
		return "预警"
	case 2:
		return "报警"
	case 3:
		return "违章"
	case 4:
		return "故障"
	default:
		return "未知"
	}
}

// 解析风速状态
func parseWindspeedStatus(status uint32) string {
	switch status {
	case 0:
		return "正常"
	case 1:
		return "预警"
	case 2:
		return "报警"
	case 4:
		return "故障"
	default:
		return "未知"
	}
}

// 解析幅度状态
func parseAmplitudeStatus(status uint32) string {
	switch status {
	case 0:
		return "正常"
	case 1:
		return "近端预警"
	case 2:
		return "近端报警"
	case 4:
		return "故障"
	case 9:
		return "远端预警"
	case 10:
		return "远端报警"
	default:
		return "未知"
	}
}

// 解析高度状态
func parseHightStatus(status uint32) string {
	switch status {
	case 0:
		return "正常"
	case 1:
		return "预警"
	case 2:
		return "报警"
	case 4:
		return "故障"
	default:
		return "未知"
	}
}

// 解析倾角状态
func parseInclinationStatus(status uint32) string {
	switch status {
	case 0:
		return "正常"
	case 2:
		return "报警"
	default:
		return "未知"
	}
}

// 解析回转状态
func parseRotationStatus(status uint32) string {
	switch status {
	case 0:
		return "正常"
	case 1:
		return "左限位预警"
	case 2:
		return "左限位报警"
	case 4:
		return "故障"
	case 9:
		return "右限位预警"
	case 10:
		return "右限位报警"
	default:
		return "未知"
	}
}

// 校验和验证
func validateChecksum(data []byte) error {
	if len(data) < 5 {
		return fmt.Errorf("data length is too short to contain a checksum")
	}

	// Calculate checksum excluding the last five bytes
	var calculatedChecksum byte
	for i := 0; i < len(data)-5; i++ {
		calculatedChecksum += data[i]
	}

	// Get the checksum byte from the original data
	originalChecksum := data[len(data)-5]

	// Compare calculated checksum with the original checksum
	if calculatedChecksum != originalChecksum {
		return fmt.Errorf("checksum mismatch! calculated: %02x, original: %02x", calculatedChecksum, originalChecksum)
	}

	fmt.Printf("校验和匹配! 计算得: %02x, 本来为: %02x\n", calculatedChecksum, originalChecksum)
	return nil
}
func Response(data []byte, frameType uint) []byte {
	var data_res []byte
	switch frameType {
	case 0x01:
		data[5] = 0x01
	case 0x03:
		data[5] = 0x03
	case 0x07:
		data[5] = 0x07
	case 0x09:
		data[5] = 0x09
	}
	data_res = append(data[:10], data[len(data)-5:]...)
	fmt.Printf("要发送到回复帧为:%x\n", data_res)
	return data_res
}
func dataprocesee(data []byte) (string, []byte, error) {
	fmt.Println("接收到的数据长度:", len(data))
	if len(data) < 13 {
		return "", nil, fmt.Errorf("接收帧数据失败，长度不足")
	}
	validateChecksum(data)
	frameHeader := data[0:2]
	frameLength := data[2:3]
	manufacturerID := data[3:4]
	protocolVersion := data[4:5]
	frameType := data[5:6]
	deviceID := data[6:10]
	infoSegment := data[10 : len(data)-5]
	checksum := data[len(data)-5 : len(data)-4]
	frameTail := data[len(data)-4 : len(data)]

	fmt.Printf("帧头：数据[0:2]的十六进制字符串: %x\n", frameHeader)
	fmt.Printf("帧长度：数据[2:3]的十六进制字符串: %x\n", frameLength)
	fmt.Printf("厂家编号：数据[3:4]的十六进制字符串: %x\n", manufacturerID)
	fmt.Printf("协议版本：数据[4:5]的十六进制字符串: %x\n", protocolVersion)
	fmt.Printf("帧类型：数据[5:6]的十六进制字符串: %x\n", frameType)
	fmt.Printf("设备编号：数据[6:10]的十六进制字符串: %x\n", deviceID)
	fmt.Printf("信息段：数据[10:%d]的十六进制字符串: %x\n", len(data)-5, infoSegment)
	fmt.Printf("校验和：数据[%d:%d]的十六进制字符串: %x\n", len(data)-5, len(data)-4, checksum)
	fmt.Printf("帧尾：数据的十六进制字符串: %x\n", frameTail)

	switch frameType[0] {
	case 0x00:
		fmt.Println("这是一个注册信息帧数")
		Regrec_Json, err := Regrec(infoSegment)
		if err != nil {
			return "", nil, fmt.Errorf("错误转换infoSegment: %v", err)
		}
		data_res := Response(data, 0x01)
		return Regrec_Json, data_res, nil
	case 0x02:
		fmt.Println("这是一个设备信息参数上报帧数")
		Devattri_Json, err := Devattri(infoSegment)
		if err != nil {
			return "", nil, fmt.Errorf("解析infoSegment失败: %v", err)
		}
		data_res := Response(data, 0x03)
		return Devattri_Json, data_res, nil
	case 0x06:
		fmt.Println("这是一个设备实时数据上传帧数")
		Devreal_Json, err := devreal(infoSegment)
		if err != nil {
			return "", nil, fmt.Errorf("解析infoSegment失败: %v", err)
		}
		data_res := Response(data, 0x07)
		return Devreal_Json, data_res, nil
		// 在这里添加返回值，如果需要的话
	case 0x08:
		fmt.Println("这是一个吊装数据上传帧数")
		hoistingdata_Json, err := hoistingdata(infoSegment)
		if err != nil {
			return "", nil, fmt.Errorf("解析infoSegment失败: %v", err)
		}
		data_res := Response(data, 0x09)
		return hoistingdata_Json, data_res, nil
	default:
		return "", nil, fmt.Errorf("未知帧类型")
	}

	return "", nil, nil // 如果没有需要返回的内容，可以返回空字符串和 nil
}

func sendDataToWebSocket(dataJSON string) {
	// 将数据发送给 WebSocket 服务器
	for client := range wsClients {
		err := client.WriteMessage(websocket.TextMessage, []byte(dataJSON))
		if err != nil {
			fmt.Println("Error writing message to WebSocket client:", err)
			client.Close()
			delete(wsClients, client)
		}
	}
}

func handleTCPConnection(conn net.Conn) {
	defer conn.Close()

	// 创建一个缓冲区来存储接收到的数据
	buffer := make([]byte, 1024)
	for {
		n, err := conn.Read(buffer)
		if err != nil {
			if err == io.EOF {
				fmt.Println("Client closed connection:", err)
			} else {
				fmt.Println("Error reading from connection:", err)
			}
			return
		}

		// 处理接收到的数据
		data := buffer[:n]
		fmt.Println("Received data from TCP client:", hex.EncodeToString(data))
		//处理数据
		data_Json, data_res, err := dataprocesee(data) //处理数据
		if err != nil {
			fmt.Println("Error processing data:", err)
			continue
		}
		conn.Write(data_res)
		// 将数据发送给 WebSocket 服务器
		sendDataToWebSocket(data_Json)
	}
}

func main() {
	// 启动 TCP 服务器监听端口
	go func() {
		ln, err := net.Listen("tcp", ":8080")
		if err != nil {
			fmt.Println("Error starting TCP server:", err)
			os.Exit(1)
		}
		defer ln.Close()

		fmt.Println("TCP server listening on port 8080")

		for {
			// 接受客户端连接
			conn, err := ln.Accept()
			if err != nil {
				fmt.Println("Error accepting connection:", err)
				continue
			}

			// 处理客户端连接
			go handleTCPConnection(conn)
		}
	}()

	// 设置 WebSocket 路由
	http.HandleFunc("/ws", handleWebSocket)

	// 启动 WebSocket 服务器
	fmt.Println("WebSocket server running on localhost:8081")
	err := http.ListenAndServe(":8081", nil)
	if err != nil {
		fmt.Println("Error starting WebSocket server:", err)
		return
	}
}
